<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter';

import { ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';

import {
  Button,
  InputSearch,
  message,
  Modal,
  Popconfirm,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter';
import { deleteRoleById, getRolesApi } from '#/api/core/role';
import { $t } from '#/locales';

import NewRole from './role-drawer.vue';

const [BaseDrawer, baseDrawerApi] = useVbenDrawer({
  connectedComponent: NewRole,
});

function openNewDrawer() {
  baseDrawerApi.setData({}); // 清空数据
  baseDrawerApi.open();
}

interface RoleType {
  value: string;
  desc: string;
  id: string;
  attr: string;
  createTime: string;
  updateTime: string;
}

const searchText = ref('');
const selectedRows = ref<RoleType[]>([]);

const gridOptions: VxeGridProps<RoleType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
    checkMethod: ({ row }) => row.attr === 'rw', // 复选框是否可选
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    {
      align: 'left',
      field: 'name',
      title: $t('role.columns.name'),
      type: 'checkbox',
    },
    { field: 'description', title: $t('role.columns.description') },
    { field: 'createTime', title: $t('role.columns.createTime') },
    { field: 'updateTime', title: $t('role.columns.updateTime') },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: $t('role.columns.action'),
      width: 140,
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return await getRolesApi({
          page: page.currentPage,
          pageSize: page.pageSize,
          search: searchText.value,
        });
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

async function deleteRole(row: RoleType) {
  try {
    await deleteRoleById(row.id); // 等待删除操作完成
    await gridApi.reload(); // 等待表格刷新完成
    message.success($t('common.action.deleteSuccess'));
  } catch {
    message.error($t('common.submit.failed'));
  }
}

function editRole(row: RoleType) {
  baseDrawerApi.setData(row); // 设置抽屉的数据
  baseDrawerApi.open();
}

function handleSave() {
  gridApi.reload(); // 新增后刷新表格数据
}

function handleSearch() {
  gridApi.reload(); // 按回车后刷新表格数据
}

function handleDeleteSelected() {
  if (selectedRows.value.length === 0) return;

  const ids = selectedRows.value.map((row) => row.id);

  Modal.confirm({
    title: $t('role.delete.title'),
    content: $t('role.delete.batchConfirm', { count: ids.length }),
    okText: $t('common.yes'),
    cancelText: $t('common.no'),
    async onOk() {
      await Promise.all(ids.map((id) => deleteRoleById(id)));
      selectedRows.value = [];
      gridApi.reload();
    },
  });
}

const gridEvents = {
  checkboxChange({ records }: { records: RoleType[] }) {
    selectedRows.value = records;
  },
  checkboxAll({ records }: { records: RoleType[] }) {
    selectedRows.value = records;
  },
};
</script>

<template>
  <Page auto-content-height>
    <BaseDrawer :on-save="handleSave" />
    <Grid :grid-events="gridEvents">
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="openNewDrawer">
          {{ $t('common.action.add') }}
        </Button>
        <Button
          v-if="selectedRows.length > 0"
          class="ml-2"
          danger
          type="primary"
          @click="handleDeleteSelected"
        >
          {{ $t('common.action.delete') }}
        </Button>
      </template>
      <template #toolbar-tools>
        <InputSearch
          v-model:value="searchText"
          :placeholder="$t('common.search')"
          @search="handleSearch"
        />
      </template>
      <template #action="{ row }">
        <template v-if="row.attr !== 'r'">
          <Button type="link" @click="() => editRole(row)">
            {{ $t('common.action.edit') }}
          </Button>
          <Popconfirm
            :cancel-text="$t('common.no')"
            :ok-text="$t('common.yes')"
            :title="$t('role.delete.confirm')"
            @confirm="
              async () => {
                await deleteRole(row);
              }
            "
          >
            <Button style="color: red" type="link">
              {{ $t('common.action.delete') }}
            </Button>
          </Popconfirm>
        </template>
      </template>
    </Grid>
  </Page>
</template>
